package com.yibo.yunpicture.infrastructure.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yibo.yunpicture.infrastructure.config.CosClientConfig;
import com.yibo.yunpicture.infrastructure.api.CosManager;
import com.yibo.yunpicture.infrastructure.manager.upload.modal.dto.file.UploadPictureDTO;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 模板方法，定义上传流程
     *
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */
    public final UploadPictureDTO uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1. 校验图片
        validPicture(inputSource);
        // 2. 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFileName = getOriginalFilename(inputSource);
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFileName));
        String uploadFilePath = String.format("%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            // 3. 创建临时文件
            file = File.createTempFile(uploadFilePath, null);
            // 处理文件来源(本地或者URL)
            processFile(inputSource,file);
            // 4. 上传图片到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                CIObject compressedCiObject  = objectList.get(0);
                // 缩略图默认等于压缩图
                CIObject thumbnailCiObject  = compressedCiObject;
                if(objectList.size()>1){
                    thumbnailCiObject = objectList.get(1);
                }
                // 封装压缩图返回结果
                return buildResult(originFileName,compressedCiObject,thumbnailCiObject,imageInfo);
            }
            // 5. 封装返回结果
            return buildResult(originFileName, file, uploadFilePath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new RuntimeException(e);
        } finally {
            // 6. 清理临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 封装返回结果
     *
     * @param imageInfo
     * @param originFileName
     * @param file
     * @param uploadFilePath
     * @return
     */
    private UploadPictureDTO buildResult(String originFileName, File file, String uploadFilePath, ImageInfo imageInfo) {
        //封装返回结果
        UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureDTO.setPicName(FileUtil.mainName(originFileName));
        uploadPictureDTO.setPicSize(FileUtil.size(file));
        uploadPictureDTO.setPicWidth(picWidth);
        uploadPictureDTO.setPicHeight(picHeight);
        uploadPictureDTO.setPicScale(picScale);
        uploadPictureDTO.setPicFormat(imageInfo.getFormat());
        uploadPictureDTO.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
        uploadPictureDTO.setPicColor(imageInfo.getAve());
        return uploadPictureDTO;
    }

    /**
     * 封装压缩返回结果
     *
     * @param originFileName
     * @param compressedCiObject
     * @return
     */
    private UploadPictureDTO buildResult(String originFileName,CIObject compressedCiObject,CIObject thumbnailCiObject, ImageInfo imageInfo) {
        //封装返回结果
        UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureDTO.setPicName(FileUtil.mainName(originFileName));
        uploadPictureDTO.setPicWidth(picWidth);
        uploadPictureDTO.setPicHeight(picHeight);
        uploadPictureDTO.setPicScale(picScale);
        uploadPictureDTO.setPicFormat(compressedCiObject.getFormat());
        uploadPictureDTO.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureDTO.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureDTO.setPicColor(imageInfo.getAve());
        // 设置缩略图的URL
        uploadPictureDTO.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureDTO;
    }

    /**
     * 校验输入源(本地文件或者URL)
     *
     * @param inputSource
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginalFilename(Object inputSource);

    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 删除临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        //删除临时文件
        boolean deleteDTO = file.delete();
        if (!deleteDTO) {
            log.error("file delete error , filePath={}", file.getAbsolutePath());
        }
    }

}